package com.devo.icecream.service

import android.app.ActivityManager
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import com.devo.icecream.AppLogger
import com.devo.icecream.ui.home.HomeActivity
import com.devo.icecream.utils.LIFE_ACTION
import kotlinx.coroutines.*

//广播启动后开启的服务
class ActivityWatcherService : Service() {
    private val scope by lazy {
        CoroutineScope(Dispatchers.Default + Job())
    }
    private val manager by lazy {
        getSystemService<ActivityManager>()
    }

    private var isStop = false

    override fun onBind(p0: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        setupNotification()
        onRun()
        return START_STICKY //START_STICKY：值为常量1，service如果被干掉，会自动重启，但是onStartCommand回调方法的Intent参数为null。
    }

    private fun setupNotification() {
        val pendingIntent: PendingIntent =
            Intent(this, HomeActivity::class.java).let { notificationIntent ->
                PendingIntent.getActivity(this, 0, notificationIntent, 0)
            }

        val notification: Notification = NotificationCompat.Builder(this, "iceCream")
            .setContentTitle("ice_cream")
            .setContentText("Running...")
            .setContentIntent(pendingIntent) //点击通知的时候启动HomeActivity
            .build()

        startForeground(0x9909, notification)
    }


    private fun onRun() {
        scope.launch {
            while (true) {
                if (isStop) {
                    AppLogger.i("停止 Restart 服务")
                    break
                }
                try {
                    delay(1_000)
                    onWatch()
                } catch (e: Exception) {
                    AppLogger.e(e, "watcher error")
                }
            }
        }
    }

    private fun onWatch() {
        sendBroadcast(Intent().apply {
            action = LIFE_ACTION
            addCategory(Intent.CATEGORY_DEFAULT)
        })
    }

}